<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>

</style>

<body>
    <input type="text" placeholder="请输入你的内容">
    <button>发送请求</button>
    <div></div>
    <script>
        var input = document.querySelector('input')
        var button = document.querySelector('button')
        var div = document.querySelector('div')
        const TYPE_ENTER = 0
        const TYPE_LEAVE = 1
        const TYPE_MSG = 2
        //websocket在浏览器如何使用
        //H5已经直接提供了websocket的API，所以我们可以直接去使用
        //参数1：websocket的服务地址
        //1.创建websocket对象
        var socket = new WebSocket('ws://localhost:3000')
        //2.open：当Websocket服务器连接成功的时候触发
        socket.addEventListener('open', function () {
            div.innerHTML = '连接服务器成功'
        })

        //3.主动给websocket发送消息
        button.addEventListener('click', function () {
            var value = input.value
            socket.send(value)
            input.value = ''
        })
        //4.接收websocket服务的数据
        socket.addEventListener('message', function (e) {
            var data = JSON.parse(e.data)
            console.log(e.data)
            var dv = document.createElement('div')
            dv.innerHTML = data.msg + '--------' + data.time
            if (data.type === TYPE_ENTER){
                dv.style.color='green'
            }
            else if(data.type === TYPE_LEAVE){
                dv.style.color='red'
            }
            else{
                dv.style.color='black'
            }
                div.appendChild(dv)
        })
        socket.addEventListener('close', function () {
            div.innerHTML = '服务器断开连接'
        })
    </script>
</body>

</html>